﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Chengqbd.Core.Extensions
{
	public static class QueryableExtensions
	{
		public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, bool condition, Expression<Func<T, bool>> predicate)
		{
			bool flag = !condition;
			IQueryable<T> result;
			if (flag)
			{
				result = source;
			}
			else
			{
				result = source.Where(predicate);
			}
			return result;
		}
        
		public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, bool condition, Expression<Func<T, int, bool>> predicate)
		{
			bool flag = !condition;
			IQueryable<T> result;
			if (flag)
			{
				result = source;
			}
			else
			{
				result = source.Where(predicate);
			}
			return result;
		}
		public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, bool condition, Func<T, bool> predicate)
		{
			bool flag = !condition;
			IEnumerable<T> result;
			if (flag)
			{
				result = source;
			}
			else
			{
				result = source.Where(predicate);
			}
			return result;
		}
        
		public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, bool condition, Func<T, int, bool> predicate)
		{
			bool flag = !condition;
			IEnumerable<T> result;
			if (flag)
			{
				result = source;
			}
			else
			{
				result = source.Where(predicate);
			}
			return result;
		}
        
		public static Expression<Func<T, bool>> WhereIf<T>(this Expression<Func<T, bool>> source, bool condition, Expression<Func<T, bool>> predicate)
		{
			bool flag = !condition;
			Expression<Func<T, bool>> result;
			if (flag)
			{
				result = source;
			}
			else
			{
				result = source.And(predicate);
			}
			return result;
		}
        
		public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> source, Expression<Func<T, bool>> predicate)
		{
			InvocationExpression right = Expression.Invoke(predicate, source.Parameters);
			return Expression.Lambda<Func<T, bool>>(Expression.OrElse(source.Body, right), source.Parameters);
		}
        
		public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> source, Expression<Func<T, bool>> predicate)
		{
			InvocationExpression right = Expression.Invoke(predicate, source.Parameters);
			return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(source.Body, right), source.Parameters);
		}
	}
}
